package com.cee.util;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeanWrapper;
import org.springframework.beans.BeanWrapperImpl;

import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.*;

public class BeanUtil {
    
    /**
     * 方法说明：将bean转化为另一种bean实体
     *
     * @param object
     * @param entityClass
     * @return
     */
    public static <T> T convertBean(Object object, Class<T> entityClass) {
        if (null == object) {
            return null;
        }
        
        return copy(object, entityClass);
    }
    public static String format(Object obj) {
        if (obj == null) {
            return null;
        } else {
            if (obj instanceof Date) {
                return DateUtil.format((Date)obj, DateUtil.DATE_TIME_PATTERN);
            } else {
                return obj.toString();
            }
        }
    }

    /**
     * 方法说明：对象转换
     *
     * @param source 原对象
     * @param target 目标对象
     * @param ignoreProperties 排除要copy的属性
     * @return
     */
    public static <T> T copy(Object source, Class<T> target, String... ignoreProperties) {
        T targetInstance = null;
        try {
            targetInstance = target.newInstance();
        }
        catch (Exception e) {
            e.printStackTrace();
        }
        if (ArrayUtils.isEmpty(ignoreProperties)) {
            BeanUtils.copyProperties(source, targetInstance);
        } else {
            BeanUtils.copyProperties(source, targetInstance, ignoreProperties);
        }
        return targetInstance;
    }
    
    /**
     * 複製時忽略null的字段
     * 
     * @param src
     * @param target
     */
    public static void copyProperties(Object src, Object target) {
        BeanUtils.copyProperties(src, target);
    }
    
    /**
     * 複製時忽略null的字段
     * 
     * @param src
     * @param target
     */
    public static void copyPropertiesIgnoreNull(Object src, Object target) {
        BeanUtils.copyProperties(src, target, getEmptyFieldNameArray(src));
    }
    
    /**
     * 取得null的字段
     * 
     * @param source
     * @return
     */
    private static String[] getEmptyFieldNameArray(Object source) {
        final BeanWrapper src = new BeanWrapperImpl(source);
        PropertyDescriptor[] pds = src.getPropertyDescriptors();
        
        Set<String> emptyNames = new HashSet<String>();
        for (PropertyDescriptor pd : pds) {
            Object srcValue = src.getPropertyValue(pd.getName());
            if (srcValue == null) {
                emptyNames.add(pd.getName());
            }
        }
        String[] result = new String[emptyNames.size()];
        return emptyNames.toArray(result);
    }
    
    public static List<String> getEmptyFieldNames(Object source) {
        List<String> fields = new ArrayList<String>();
        String[] nullFiledNames = getEmptyFieldNameArray(source);
        for (String filedName : nullFiledNames) {
            fields.add(filedName);
        }
        
        return fields;
    }
    
    /**
     * 方法说明：对象转换(List)
     *
     * @param list 原对象
     * @param target 目标对象
     * @param ignoreProperties 排除要copy的属性
     * @return
     */
    public static <T, E> List<T> copyList(List<E> list, Class<T> target, String... ignoreProperties) {
        List<T> targetList = new ArrayList<>();
        if (CollectionUtils.isEmpty(list)) {
            return targetList;
        }
        for (E e : list) {
            targetList.add(copy(e, target, ignoreProperties));
        }
        return targetList;
    }
    
    /**
     * 方法说明：map转化为对象
     *
     * @param map
     * @param t
     * @return
     * @throws InstantiationException
     * @throws IllegalAccessException
     * @throws InvocationTargetException
     */
    public static <T> T mapToObject(Map<String, Object> map, Class<T> t)
        throws InstantiationException, IllegalAccessException, InvocationTargetException {
        T instance = t.newInstance();
        org.apache.commons.beanutils.BeanUtils.populate(instance, map);
        return instance;
    }
    
    /**
     * Converts a JavaBean to a map.
     *
     * @param bean JavaBean to convert
     * @return map converted
     * @throws IntrospectionException failed to get class fields
     * @throws IllegalAccessException failed to instant JavaBean
     * @throws InvocationTargetException failed to call setters
     */
    public static final Map<String, Object> toMap(Object bean)
        throws IntrospectionException, IllegalAccessException, InvocationTargetException {
        Map<String, Object> returnMap = new HashMap<String, Object>();
        BeanInfo beanInfo = Introspector.getBeanInfo(bean.getClass());
        PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
        for (int i = 0; i < propertyDescriptors.length; i++) {
            PropertyDescriptor descriptor = propertyDescriptors[i];
            String propertyName = descriptor.getName();
            if (!(propertyName.equals("class") || propertyName.equals("declaringClass"))) {
                Method readMethod = descriptor.getReadMethod();
                Object result = readMethod.invoke(bean, new Object[0]);
                if (result != null) {
                    returnMap.put(propertyName, result);
                } else {
                    returnMap.put(propertyName, "");
                }
            }
        }
        return returnMap;
    }

    public static final Map<String, Object> toMapWithNullValue(Object bean)
            throws IntrospectionException, IllegalAccessException, InvocationTargetException {
        Map<String, Object> returnMap = new HashMap<String, Object>();
        BeanInfo beanInfo = Introspector.getBeanInfo(bean.getClass());
        PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
        for (int i = 0; i < propertyDescriptors.length; i++) {
            PropertyDescriptor descriptor = propertyDescriptors[i];
            String propertyName = descriptor.getName();
            if (!(propertyName.equals("class") || propertyName.equals("declaringClass"))) {
                Method readMethod = descriptor.getReadMethod();
                Object result = readMethod.invoke(bean, new Object[0]);
                if (result != null) {
                    returnMap.put(propertyName, result);
                } else {
                    returnMap.put(propertyName, null);
                }
            }
        }
        return returnMap;
    }
    
    public static final Map<String, Object> toMapIgnoreEmptyField(Object bean)
        throws IntrospectionException, IllegalAccessException, InvocationTargetException {
        Map<String, Object> returnMap = new HashMap<String, Object>();
        BeanInfo beanInfo = Introspector.getBeanInfo(bean.getClass());
        PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
        for (int i = 0; i < propertyDescriptors.length; i++) {
            PropertyDescriptor descriptor = propertyDescriptors[i];
            String propertyName = descriptor.getName();
            if (!(propertyName.equals("class") || propertyName.equals("declaringClass"))) {
                Method readMethod = descriptor.getReadMethod();
                Object result = readMethod.invoke(bean, new Object[0]);
                if (result != null && result.toString().length() > 0) {
                    if (String.class.equals(result.getClass())) {
                        String str = (String)result;
                        if (StringUtils.isNotEmpty(str)) {
                            returnMap.put(propertyName, result);
                        }
                    } else {
                        returnMap.put(propertyName, result);
                    }
                }
            }
        }
        return returnMap;
    }
    
    public static boolean containsField(Object obj, String fieldName) {
        if (obj == null) {
            throw new IllegalArgumentException("obj is null");
        }
        
        try {
            PropertyDescriptor pd = new PropertyDescriptor(fieldName, obj.getClass());
            Method getMethod = pd.getReadMethod();// 获得get方法
            if (getMethod == null) {
                return false;
            }
            return true;
        }
        catch (Exception e) {
            return false;
        }
    }
    
    public static Object getFieldValue(Object obj, String fieldName) {
        if (obj == null) {
            throw new IllegalArgumentException("obj is null");
        }
        
        try {
            PropertyDescriptor pd = new PropertyDescriptor(fieldName, obj.getClass());
            Method getMethod = pd.getReadMethod();// 获得get方法
            return getMethod.invoke(obj);
        }
        catch (Exception e) {
            return null;
        }
    }
    
    public static void setFieldValue(Object obj, String fieldName, Object fieldValue) {
        if (obj == null) {
            throw new IllegalArgumentException("obj is null");
        }
        
        try {
            PropertyDescriptor pd = new PropertyDescriptor(fieldName, obj.getClass());
            Method writeMethod = pd.getWriteMethod();
            if (String.class.equals(pd.getPropertyType())) {
                writeMethod.invoke(obj, fieldValue.toString());
            } else {
                writeMethod.invoke(obj, fieldValue);
            }
            
        }
        catch (Exception e) {
            throw new IllegalStateException(e);
        }
    }

    public static String getPropName(Object obj, Class<? extends Annotation> annotationClass) {
        Class<? extends Object> class1 = obj.getClass();
        while (!class1.equals(Object.class)) {
            if (class1.getSuperclass().equals(Object.class)) {
                break;
            }
            class1 = class1.getSuperclass();
        }

        Field[] fields = class1.getDeclaredFields();

        List<String> rowIds = new ArrayList<>();
        for (int i = 0; i < fields.length; i++) {
            Annotation annotation = fields[i].getAnnotation(annotationClass);
            if (annotation != null) {
                fields[i].setAccessible(true);
                try {
                    return fields[i].getName();
                }
                catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }
    
    public static String getPropValueByAnnotation(Object obj, Class<? extends Annotation> annotationClass) {
        
        Class<? extends Object> class1 = obj.getClass();
        while (!class1.equals(Object.class)) {
            if (class1.getSuperclass().equals(Object.class)) {
                break;
            }
            class1 = class1.getSuperclass();
        }
        
        Field[] fields = class1.getDeclaredFields();
        
        List<String> rowIds = new ArrayList<>();
        for (int i = 0; i < fields.length; i++) {
            Annotation annotation = fields[i].getAnnotation(annotationClass);
            if (annotation != null) {
                fields[i].setAccessible(true);
                try {
                    Object value = fields[i].get(obj);
                    if (value != null) {
                        rowIds.add(value.toString());
                    }
                }
                catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        if (rowIds.isEmpty()) {
            return null;
        }
        return org.springframework.util.StringUtils.collectionToDelimitedString(rowIds, "-");
    }

    
    public static Object getPropertyValue(Object object, String fieldName)
        throws Exception {
        if (object == null) {
            return null;
        }
        if (StringUtils.isBlank(fieldName)) {
            return null;
        }
        Field field = null;
        Class<?> clazz = object.getClass();
        for (; clazz != Object.class; clazz = clazz.getSuperclass()) {
            try {
                field = clazz.getDeclaredField(fieldName);
                field.setAccessible(true);
                return field.get(object);
            }
            catch (Exception e) {
                // 这里甚么都不要做！并且这里的异常必须这样写，不能抛出去。
                // 如果这里的异常打印或者往外抛，则就不会执行clazz = clazz.getSuperclass(),最后就不会进入到父类中了
            }
        }
        return null;
    }
}
